import type { ResponseData, ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import { request } from 'umi';
import type { AddItem, DetailItem, EditItem, QueryListParams, TableListItem } from './data.d';

type Pagination = { page?: number; pageSize?: number };

/**
 * 获取客户角色列表
 * @param params
 */
export async function queryTenantRoleList(
  params: Pagination & QueryListParams,
): Promise<RequestData<TableListItem>> {
  const { page = 1, pageSize = 20, name = undefined } = params;
  const res: ResponsePaginationData<{
    id: any;
    name: string;
    accesses?: { id: string; name: string }[];
  }> = await request('/tenant/role/list', {
    params: { page, pageSize, name },
  });

  return {
    success: true,
    total: res.data.total,
    data: res.data.list.map((item) => ({
      ...item,
      accesses: item.accesses?.map((obj) => ({ id: obj.id, code: '', name: obj.name })),
    })),
  };
}

export async function querytenantRoleDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: DetailItem }> {
  const res = await request(`/tenant/role/${params.id}`);

  if (res?.code !== SUCCESS_CODE) {
    return { success: false };
  }

  return {
    success: true,
    data: {
      id: res.data.id,
      name: res.data.name,
      accesses: res.data.accesses?.map(({ id, name }: { id: string; name: string }) => ({
        id,
        code: '',
        name,
      })),
    },
  };
}

/**
 * 创建一个客户角色
 * @param params
 */
export async function addTenantRole(params: AddItem) {
  const { name } = params;

  return request('/tenant/role/', {
    method: 'POST',
    data: { name },
  });
}

export async function editTenantRole(params: EditItem) {
  const { id, name } = params;

  return request(`/tenant/role/${id}`, { data: { name }, method: 'PUT' });
}

export async function editTenantRoleAccesses(params: EditItem) {
  const { id, accesses } = params;

  const accessIds = accesses?.map((acc) => acc.id);

  return request(`/tenant/role/${id}/accesses`, { data: { accessIds }, method: 'PUT' });
}

export async function removetenantRole(params: { id: string }): Promise<void> {
  const res: ResponseData<any> = await request(`/tenant/role/${params.id}`, { method: 'DELETE' });

  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}

export async function queryTenantRoleAccessList(params: { userId: string }) {
  const res: ResponsePaginationData<{
    id: string;
    name: string;
    code: string;
  }> = await request(`/tenant/tenant/${params.userId}/roles/`);
  return {
    success: true,
    total: res.data.list.length,
    data: res.data.list,
  };
}
